package com.songminju.jsong_beanwithsql;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import javax.sql.DataSource;

import com.songminju.jdagger.io.IoClose;
import com.songminju.jsong_beanwithsql.crud.CrudOption1;
import com.songminju.jsong_beanwithsql.crud.CrudType;

/**
@todo
@description
@author songminju
@date 2017年12月3日
*/
public abstract class SqlBeanDao<T> {
	
	private Class<T> entityClass = null;
	private DataSource ds = null;
	
	protected String tableName;
	private ThreadLocal<CrudOption1> threadCrudOption = new ThreadLocal<>();
	
	@SuppressWarnings("unchecked")
	public SqlBeanDao(DataSource ds) {
		this.ds = ds;
		@SuppressWarnings("rawtypes")
		Class c = this.getClass();
		Type t = c.getGenericSuperclass();
		if(t instanceof ParameterizedType) {
			Type[] params = ((ParameterizedType)t).getActualTypeArguments();
			this.entityClass = ((Class<T>)params[0]);
		}
	}
	
	private CrudOption1 createCrudOption(CrudType operation,String fields) {
		CrudOption1 crudOption =  new CrudOption1(operation,fields,tableName);
		threadCrudOption.set(crudOption);
		return crudOption;
	}
	
	public final CrudOption1 query(String fields) {
		return createCrudOption(CrudType.SELECT, fields);
	}
	
	public final CrudOption1 insert(String fields) {
		return createCrudOption(CrudType.INSERT, fields);
	}
	
	public final void execVoid() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = ds.getConnection();
			CrudOption1 co = threadCrudOption.get();
			ps = conn.prepareStatement(co.sql.toString());
			Object[] values = co.getValues();
			if(values != null) {
				for(int i=0;i<values.length;i++) {
					ps.setObject(i+1, values[i]);
				}
			}
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			IoClose.close(rs,ps,conn);
		}
	}
	/*
	T first();
	long update();
	List<T> all();
	long count();*/
}
